package drds.server.net.packet;

import java.nio.ByteBuffer;

import drds.server.net.SessionContext$LifeCycle;

/**
 * From server to client during initial handshake.
 * 
 * <pre>
 * Bytes                        Name
 * -----                        ----
 * 1                            protocol_version
 * n (Null-Terminated String)   server_version
 * 4                            thread_id
 * 8                            scramble_buff
 * 1                            (filler) always 0x00
 * 2                            server_capabilities
 * 1                            server_language
 * 2                            server_status
 * 13                           (filler) always 0x00 ...
 * 13                           rest of scramble_buff (4.1)
 * 
 * @see http://forge.mysql.com/wiki/MySQL_Internals_ClientServer_Protocol#Handshake_Initialization_Packet
 * </pre>
 * 
 * @author 曹正辉<330937205@qq.com>
 * 
 */
public class ShakeHandPacket extends Packet {
	public byte protocolVersion;
	public byte[] serverVersion;
	public long sessionContextId;
	public byte[] seed;

	public void read(BinaryPacket binaryPacket) {
		packetLength = binaryPacket.packetLength;
		packetId = binaryPacket.packetId;
		BytesHolder bytesHolder = new BytesHolder(binaryPacket.bytes);
		protocolVersion = bytesHolder.read();
		serverVersion = bytesHolder.readBytesWithNull();
		sessionContextId = bytesHolder.readLong4();
		seed = bytesHolder.readBytesWithNull();

	}

	public void read(byte[] bytes) {
		BytesHolder bytesHolder = new BytesHolder(bytes);
		packetLength = bytesHolder.readInt3();
		packetId = bytesHolder.read();
		protocolVersion = bytesHolder.read();
		serverVersion = bytesHolder.readBytesWithNull();
		sessionContextId = bytesHolder.readLong4();
		seed = bytesHolder.readBytesWithNull();

	}

	public void write(SessionContext$LifeCycle sessionContext) {
		ByteBuffer byteBuffer = sessionContext.allocate();
		ByteBufferUtil.writeInt3(byteBuffer, computePacketSize());
		byteBuffer.put(packetId);
		byteBuffer.put(protocolVersion);
		ByteBufferUtil.writeWithNull(byteBuffer, serverVersion);
		ByteBufferUtil.writeLong4(byteBuffer, sessionContextId);
		ByteBufferUtil.writeWithNull(byteBuffer, seed);

		sessionContext.write(byteBuffer);
	}

	@Override
	public int computePacketSize() {
		int size = 1;
		size += serverVersion.length;// n
		size += 5;// 1+4
		size += seed.length;// 8
		size += 19;// 1+2+1+2+13
		size += 1;// 1
		return size;
	}

	public void write() {

	}

}